// pages/voiceAssistant/voiceAssistant.js
import {getToken, soundRecoPro} from '../../utils/baidu_api'
const recorderManager = wx.getRecorderManager()  // 获取全局唯一的录音管理器 RecorderManager
const innerAudioContext = wx.createInnerAudioContext()  // 创建内部 audio 上下文 InnerAudioContext 对象。
let plugin = requirePlugin("QCloudAIVoice");  //引入语音识别插件
plugin.setQCloudSecret(1307249781, "AKIDGdM3b98tQimeLrBG6lCaptlRufU8Zqxg", "jIkBTbWEoGVWRCj3EDyWu66tVxIiz88x", false);//设置腾讯云账号信息，其中appid是数字，secret是字符串，openConsole是布尔值(true/false)，为控制台打印日志开关
let manager = plugin.getRecordRecognitionManager();
let speechRecognizerManager = plugin.speechRecognizerManager();
const app = getApp()
var init 
const params = {
  signCallback: null, // 鉴权函数
  // 用户参数
  secretkey: 'jIkBTbWEoGVWRCj3EDyWu66tVxIiz88x',
  secretid:  'AKIDGdM3b98tQimeLrBG6lCaptlRufU8Zqxg',
  appid: '1307249781',
  // 录音参数
  duration: 10000,
  frameSize: 0.32,  //单位:k

  // 实时识别接口参数
  engine_model_type : '16k_zh',
  // 以下为非必填参数，可跟据业务自行修改
  // hotword_id : '08003a00000000000000000000000000',
  // needvad: 0,
  // filter_dirty: 1,
  // filter_modal: 2,
  // filter_punc: 0,
  // convert_num_mode : 1,
  // word_info: 2,
  // vad_silence_time: 200,
  // token: ''  // 若密钥为临时密钥，需传此参数
};
 
const options = {
  duration: 30000,
  sampleRate: 32000,
  numberOfChannels: 1,
  encodeBitRate: 64000,
  format: 'mp3',
  frameSize: 6
}
function mp3ToPcm(mp3AB){
  var that = this
  var decoder = Mp3.newDecoder(mp3AB)
}

function sendRecord(src){
  var obj = {
    // 已经在花生壳中映射到本地端口-3001 
    url: "http://127.0.0.1:3001/post",
    filePath: src,
    name: "fffile",
    header: {
      'Content-Type': 'application/json'
    },
    success: function (result) {
      var data = JSON.parse(result.data);
      // msg 为最终语音识别的字符串
      var msg = data.result;
      // 获取当前页面对象
      var page = getCurrentPages()[0];
      page.setData({ msg: msg });
    },
    fail: function (err) {
      console.log(err);
    }
  };
  wx.uploadFile(obj)
}
// 结束录音的时候触发 
const that = this
recorderManager.onStop((res) => {
  // 获取文件路径-提交到后台-后台发送到百度
  // sendRecord(res.tempFilePath);

  const tempFilePath = res.tempFilePath
  const fs = wx.getFileSystemManager()
  fs.readFile({
    filePath: tempFilePath,
    success(res){
      console.log("read success")
      that.mp3ToPcm(res.data)
    },
    fail(e){
      console.log("read fail")
      console.log(e)
    }
  })
})

recorderManager.onError((res) => {
  console.log("error", res);
});


Page({
 
  /**
   * 页面的初始数据
   */
  data: {
     time: 0, // 初始时间
    duration: 60000, // 录音时长为1分钟
    status: 0,  // 语音识别管理器的状态：1为开始，2为停止，
    voiceData:"" ,//语音识别阶段数据,
    resultNumber:1,//识别结果的段数
    Words:'',
    text:'',
    oldText:'', // 上一次的文字内容
    noSound:false, // 没有声音
    isVoice:false, // 语音中
    voice:false,
    inter:'',
    inputVal : '',
    msgList : [],
    windowWidth : wx.getSystemInfoSync().windowWidth,
    windowHeight : wx.getSystemInfoSync().windowHeight,
    keyHeight : 0,
    job_details: '',

    audio_path: "",
    audio_data: undefined,
    recognize_result: "",
    sms:""
 },

 initData: function (that) {
    var text = '您好，欢迎使用智能语音助手！'
    var msgList = [{
        speaker: 'server',
        contentType: 'text',
        content: text
      }
      // ,
      // {
      //   speaker: 'customer',
      //   contentType: 'text',
      //   content: '我怕是走错片场了...'
      // }
    ]
    that.setData({
      msgList : msgList,
    })
    // this.speech(text)
  },

  onLoad: function (options) {
    this.initData(this)
    // 开始识别
    speechRecognizerManager.OnRecognitionStart = (res) => {
      console.log('开始识别', res);
    }
    // 一句话开始
    speechRecognizerManager.OnSentenceBegin = (res) => {
      console.log('一句话开始', res)
    }
    // 识别变化时
    speechRecognizerManager.OnRecognitionResultChange = (res) => {
      console.log('识别变化时', res)
    }
    // 一句话结束
    speechRecognizerManager.OnSentenceEnd = (res) => {
      console.log('一句话结束', res)
    }
    // 识别结束
    speechRecognizerManager.OnRecognitionComplete = (res) => {
      console.log('识别结束', res);
    }
    // 识别错误
    speechRecognizerManager.OnError = (res) => {
      console.log('识别失败', res);
    }
    // 录音结束（最长10分钟）时回调
    speechRecognizerManager.OnRecorderStop = (res) => {
      console.log('录音结束', res);
    }
  },
  //封装语音合成函数，只需传入text
  speech: function(text){
    plugin.textToSpeech({
      content: text,
      speed: 0,
      volume: 0,
      voiceType: 4,
      language: 1,
      projectId: 0,
      sampleRate: 16000,

      success: function(data) {
              let url = data.result.filePath;
              if(url && url.length > 0){
                      innerAudioContext.autoplay = true;
                      innerAudioContext.src = url;
                      innerAudioContext.onPlay(() => {
                      });
                      innerAudioContext.onError((res) => {
                          console.log(res.errMsg)
                      });
              }
      },
      fail: function(error){
          console.log(error);
      }
  })
  },
 
  beginRecord: function(){
    // this.data.inter =  setInterval(() => {
    //   this.setData({
    //     isVoice:true,
    //     voice:!this.data.voice
    //   })
    // }, 600)
    // console.log('start');
    // this.setData({
    //   oldText:this.data.job_details
    // })
    //   var that=this
    //   clearInterval(init) // 取消之前的计时
    //   this.timeCounter()  // 开始计时
      //开始识别
      // speechRecognizerManager.start(params);
      const options = {
        sampleRate: 16000,
        numberOfChannels: 1,
        format: "PCM"
      };
      recorderManager.start(options);
      recorderManager.onStart(() =>{
        console.log("Recording!---")
      })
  },

    endRecord: function(){
      // clearInterval(this.data.inter)
      // this.setData({
      //   voice:false,
      //   isVoice:false
      // })
      // speechRecognizerManager.stop()
      recorderManager.stop()
      recorderManager.onStop(res=>{
        this.audio_path = res.tempFilePath;
        console.log("audio path:" + res.tempFilePath)
        // 这里借鉴了一位大佬的方案
        const fs = wx.getFileSystemManager();
        fs.readFile({
          filePath: this.audio_path,
          success: (res)=>{
            this.audio_data = res.data;
          }
        });
      });
      this.soundRecognize()
    },

    soundRecognize(){
      soundRecoPro(this.audio_data).then(res =>{
        console.log(res);
        this.setData({
          recognize_result: res,
          sms: res
        })
      })
    },
    send(){
      var that = this
      var customer = {
        speaker: 'customer',
        contentType: 'text',
        content: this.data.sms
      }
      this.setData({
        msgList: this.data.msgList.concat(customer),
      })
      wx.request({
        url: 'http://10.128.211.123:9999',
        method:'POST',
        data: that.data.sms,
        header:{
          'content-type':'application/x-www-form-urlencoded',
          //'Content-Type':'application/json',
          // "X-AjaxPro-Method":"ShowList"
        },
        success: function(res){
          console.log(res.data)
          var newServer = {
            speaker:'server',
            contentType:'text',
            content: res.data
          }
          that.setData({
            msgList: that.data.msgList.concat(newServer)
          })
          that.speech(res.data)
        }
      })
      this.setData({
        sms: ""
      })
    },
  
// 方法
  timeCounter: function(time) {  // 定义一个计时器函数
    var that = this
    if (time == undefined) {
   
      init = setInterval(function() { // 设定一个计时器ID。按照指定的周期（以毫秒计）来执行注册的回调函数
        var time = that.data.time + 1; // 每秒钟计时+1
        that.setData({
          time: time
        })
      }, 1000);
    } else {
      clearInterval(init) // 取消计时
      console.log("暂停计时")
    }
  },
  timeCounter: function(time) {  // 定义一个计时器函数
    var that = this
    if (time == undefined) {
   
      init = setInterval(function() { // 设定一个计时器ID。按照指定的周期（以毫秒计）来执行注册的回调函数
        var time = that.data.time + 1; // 每秒钟计时+1
        that.setData({
          time: time
        })
      }, 1000);
    } else {
      clearInterval(init) // 取消计时
      console.log("暂停计时")
    }
  },
  mytouchstart(){
   this.data.inter =  setInterval(() => {
      this.setData({
        isVoice:true,
        voice:!this.data.voice
      })
    }, 600)
    console.log('start');
    this.setData({
      oldText:this.data.form.job_details
    })
      var that=this
      clearInterval(init) // 取消之前的计时
      this.timeCounter()  // 开始计时
      //开始识别
      manager.start({
        duration:this.data.duration, 
        engine_model_type: '16k_zh',
        format: 'acc'
        // 以下为非必填参数，可跟据业务自行修改
        // hotword_id = '08003a00000000000000000000000000',
        // filter_dirty = 0,
        // filter_modal = 0,
        // filter_punc = 0,
        // convert_num_mode = 0,
        // needvad = 1
        });
      //获取识别内容
      manager.onRecognize((res) => {
        if(res.result || res.resList){
            console.log("识别结果", res.result);
              that.setData({
                    'form.job_details':this.data.oldText +  res.result,
                })
              // clearInterval(this.data.clearId)
             
        }else if(res.errMsg){
            console.log("recognize error", res.errMsg);
        }
  })
  },
  mytouchend(){
    clearInterval(this.data.inter)
      this.setData({
        voice:false,
        isVoice:false
      })
    manager.stop();
  },
  inputText(e){
    console.log(e);
    let str = this.data.text
    this.setData({
      text:e.detail.value
    })
  }
})